<?php
class Default_Model_User extends Zend_Db_Table{

	protected $_name = USER_TABLE;
	protected $_primary = 'user_id';

	private $USER_ID = 'user_id';
	private $USER_EMAIL = 'email';
	private $USER_FULL_NAME = "fullname";
	private $USER_ADDRESS = "address";
	private $USER_PHONE = "phone";
	private $USER_CREATED_TIME = "created_time";
	private $USER_PWD = "password";

	protected $db;

	public function __construct(){
		//Goi ket noi voi Zend Db
		$this->db = Zend_Registry::get('connectDB');
	}

	protected $_messageError = null;

	public function countUser(){
		$select = $this->db->select()
		->from(USER_TABLE,array('COUNT(user_id) AS totalUser'));
		$result = $this->db->fetchOne($select);
		return $result;
	}

	public function listAllUser(){
		$select = $this->db->select()->from(USER_TABLE);
		$select->order($this->USER_ID.' DESC');
		return $select;
	}

	public function getUserInfoById($userId) {
		$select = $this->db->select()->from(USER_TABLE)->where($this->USER_ID.' = ?',$userId);
		$result  = $this->db->fetchAll($select);
		return $result;
	}

	// check password
	public function checkPwd($uerId, $pwd) {
		$select = $this->db->select()->from(USER_TABLE)->where($this->USER_ID.' = ?',$uerId)->where($this->USER_PWD.' = ?',md5($pwd));
		$result  = $this->db->fetchAll($select);
		return $result;
	}

	// check email
	public function checkExistingEmail($email) {
		$select = $this->db->select()->from(USER_TABLE)->where($this->USER_EMAIL.' = ?',$email);
		$result  = $this->db->fetchAll($select);
		return $result;
	}

	// update info
	public function updateUserInfo($arrParam = null, $userId){
		try {
			$this->db->update(USER_TABLE, $arrParam, $this->USER_ID.' = '.$userId);
			return true;
		} catch (Exception $e) {
			$this->_messageError = $e->getMessage();
			return false;
		}
	}

	// Them user
	public function insertUser($arrParam = null){
		try {
			$this->db->insert(USER_TABLE,$arrParam);
			return true;
		} catch (Exception $e) {
			$this->_messageError = $e->getMessage();
			return false;
		}
	}

	// Xoa thong tin user
	public function deleteUserById($userId){
		try {
			$this->db->delete(USER_TABLE,$this->USER_ID.' = ' . $userId);
			return true;
		} catch (Exception $e) {
			$this->_messageError = $e->getMessage();
			return false;
		}
	}

	// get user statistic
	public function userStatisticByMonth($month) {
		try {
			$select = $this->db->select()->from(USER_TABLE)->where($this->USER_CREATED_TIME.' LIKE "%'.$month.'%"');
			$result  = $this->db->fetchAll($select);
			return $result;
		} catch (Exception $e) {
			$this->_messageError = $e->getMessage();
		}
	}

	public function getError(){
		return $this->_messageError;
	}
}